package web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import system.StaticData;

/***
 * 控制器工具类，用于验证request是否合法
 * @author lcy
 *
 */
public abstract class AbstractControllerUtil {
	
	/***
	 * 请求校验
	 * @param request
	 * @return 是否通过校验
	 */
	public boolean validateRequest(HttpServletRequest request) {

		if (request == null)
			return false;
		
		StringBuffer url = request.getRequestURL();
		int i = url.lastIndexOf("/");
//		if("/test.do".equals(url.substring(i)))
//			return true;

		if("/system.do".equals(url.substring(i))){
			if("login".equals(request.getParameter("action")))
				return true;
		}
		

		HttpSession session = request.getSession(false);
		if (session == null)
			return false;
		
		// 验证REFERER
		if (StaticData.SYSYTEM_DENY_OUTSIDE_CONNECTION) {
			String REFERER = request.getHeader("referer");
			if (REFERER == null || REFERER.indexOf(StaticData.WEB_ADDRESS) != 0)
				return false;
		}

		// 验证Session
		if (session.getAttribute(StaticData.SESSION_USERID_NAME) == null)
			return false;
		if (!request.getRemoteAddr().equals(
				session.getAttribute(StaticData.SESSION_LOGIN_IP_NAME)))
			return false;
		Object sessionForwareIP = session
				.getAttribute(StaticData.SESSION_LOGIN_FORWARDIP_NAME);
		if (sessionForwareIP != null) {
			if (!sessionForwareIP.toString().equals(request.getHeader("x-forwarded-for")))
				return false;
		}

		// 验证是否POST请求
		return "POST".equals(request.getMethod());

	}
}
